const Router = require('koa-router')()
// const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const { moguUser } = require('../db/Schema/timor copy')
const secret = 'secret' // 令牌的盐

Router.get('/', async (ctx) => {
  // console.log('请求来了')
  // console.log(ctx.session.phone)
  // 这里必须写await
  try {
    let res = null
    let token = null
    let userInfo = null
    const table = moguUser
    console.log('sssss')
    console.log(ctx.session.phone)
    if (ctx.session.phone) {
      console.log('ttt')

      res = await table.findOne({ phone: ctx.session.phone })
      token = jwt.sign({ phone: ctx.session.phone }, secret,
        { expiresIn: '1d' } // 24小时过期
      )
      userInfo = { ...res._doc }
    } else {
      await table.create({ phone: 10000000000 })
      res = { phone: 10000000000 }
      userInfo = { res }
      // try {
      //   res = await table.findOne({ phone: 10000000000 })
      // } catch (e) {
      //   await table.create({ phone: 1000 })
      //   res = await table.findOne({ phone: 10000000000 })
      // }
    }
    // console.log(res)

    // console.log(userInfo.address)
    ctx.body = {
      code: 200,
      userInfo,
      token: token || null
    }
  } catch (err) {
    ctx.body = {
      code: 500,
      msg: '服务端错误'
    }
  }
})

module.exports = Router
